using System;
using System.Data;
using System.DirectoryServices;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Dimok.Data;
using Dimok.Web.UI;


namespace Data.DataSources {
	public class UsersDataSource : ObjectDataSourceBase {
		public override string SelectViewName { get { return ""; } }
		public override string InsertViewName { get { return ""; } }
		bool _showProfiles = false;
		public bool ShowProfiles { get { return _showProfiles; } set { _showProfiles = value; } }
		bool _showGroups = false;
		public bool ShowGroups { get { return _showGroups; } set { _showGroups = value; } }
		protected override void OnObjectCreated(object sender, ObjectDataSourceEventArgs e) {
			base.OnObjectCreated(sender, e);
			UsersDataSource me = e.ObjectInstance as UsersDataSource;
			me.ShowProfiles = ShowProfiles;
			me.ShowGroups = ShowGroups;
		}

		#region SelectAll
				public static ADsUser.th_AdsUserDataTable SelectAll() {
			return SelectAll(Dimok.Config.ADS.ApplicationDN);
		}
		public static ADsUser.th_AdsUserDataTable SelectAll(string container) {
			return ADs.LDAP.FindUsersByGroups(container,false).th_AdsUser;
		}
		#endregion
		[DataObjectMethodAttribute(DataObjectMethodType.Select,true)]
		public ADsUser.th_AdsUserDataTable SelectEx() {
			try {
				//return new ADsUser.th_AdsUserDataTable().DefaultView;
				//ADsUser dsUsers = ADs.LDAP.FindUsersByGroups(Dimok.Config.ADS.AppGroupsDN, ShowGroups);
				ADsUser dsUsers = ShowProfiles ? ADs.LDAP.FindUsersByGroups(Dimok.Config.ADS.AppGroupsDN, ShowGroups) : ADs.LDAP.FindUsersDS(ShowGroups, Dimok.Config.ADS.AppGroupsDN, true);
				ADsUser.th_AdsUserDataTable dtUsers = dsUsers.th_AdsUser;
				dtUsers.Columns.Add("DisplayName", typeof(string), "Nick");
				if (ShowProfiles) {
					Dimok.Common.TraceMe("ShowProfiles: Start");
					foreach (ADsUser.th_AdsUserRow rowUser in dtUsers) {
						//rowUser.Nick = rowUser.UserName.ToLower();
						rowUser.UserName = Dimok.User.UserObject.CurrentUserDomain.ToLower() + "\\" + rowUser.UserName.ToLower();
					}
					foreach (DataRowView row in new ProfilesDataSource().SelectEx())
						if (dtUsers.FindByUserName(row["UserName"] + "") == null)
							dtUsers.Addth_AdsUserRow(row["ID"] + "", row["Name"] + "", "", "", (row["UserName"] + "").ToLower());
					Dimok.Common.TraceMe("ShowProfiles: Stop");
				}
				if (ShowGroups) {
					Dimok.Common.TraceMe("ShowGroups: Start");
					dtUsers.Columns.Add("Groups");
					foreach (ADsUser.th_AdsUserRow rowUser in dtUsers) {
						List<string> lst = new List<string>();
						try {
							foreach (ADsUser.AdsGroupRow rowGroup in dsUsers.AdsGroup.Select("UserName='"+rowUser.UserName+"' AND dn LIKE '%"+Dimok.Config.ADS.AppGroupsDN+"%'"))
								lst.Add(rowGroup.cn);
						} catch(Exception exc) { 
							exc.Data["Name"] = rowUser.Name;
							throw;
						}
						rowUser["Groups"] = "[" + string.Join("][", lst.ToArray()) + "]";
					}
					Dimok.Common.TraceMe("ShowGroups: Stop");
				}
				//DataView dvUsers = dtUsers.DefaultView;
				//if (Where.Count > 0) dvUsers.RowFilter = string.Join(" AND ", Where.ToArray());
				//dvUsers.Sort = OrderBys.Replace("ORDER BY ","");
				ADsUser dsOut = new ADsUser();
				try {
					dsOut.Merge(dtUsers.Select("", OrderBys.Replace("ORDER BY ", "")));
				} catch (IndexOutOfRangeException) {
					dsOut.Merge(dtUsers);
				}
				return dsOut.th_AdsUser;
			} catch (Exception exc) {
				throw new Dimok.Exceptions.ASPException(exc);
			}

			//ADsUser dsUsers = ADs.LDAP.FindUsersAndGroups(Dimok.Config.ADS.AppGroupsDN);
			//DataTable dtUsers = new DataSet().Tables.Add();
			//dtUsers.Columns.Add("User");
			//dtUsers.Columns.Add("Groups");
			//dtUsers.Columns.Add("Parent");
			//dtUsers.Columns.Add("Path");
			//foreach (ADsUser.th_AdsUserRow rowUser in dsUsers.th_AdsUser) {
			//  List<string> lstGroups = new List<string>();
			//  foreach (ADsUser.AdsGroupRow rowGroup in rowUser.GetAdsGroupRows())
			//    if (!rowGroup.sam.Contains("_No_NS"))
			//      lstGroups.Add(Regex.Match(rowGroup.sam, "[^#$]+$", RegexOptions.RightToLeft).Value);
			//  dtUsers.Rows.Add(rowUser.UserName, string.Join(",", lstGroups.ToArray()), Regex.Match(rowUser.Name, "OU=([^,]+)", RegexOptions.IgnoreCase).Groups[1].Value, rowUser.Name);
			//}
			//DataView dv = dtUsers.DefaultView;
			//if (Where.Count > 0) dv.RowFilter = string.Join(" AND ", Where.ToArray());
			//return dv;
		}
	}
}